import { useConfigStore } from "@/stores/config";
import { useMasterStore } from "@/stores/master";
import { HTTPError } from "@/stores/master/error";
import { useStorageStore } from "@/stores/storage";
import { useDialog, useMessage } from "naive-ui";
import { useRoute, useRouter } from "vue-router";

export function setup() {
  const masterStore = useMasterStore();
  const configStore = useConfigStore();
  const storageStore = useStorageStore();

  const route = useRoute();
  const router = useRouter();

  const dialog = useDialog();
  const message = useMessage();
  const errorHandler = async (error: any) => {
    console.error(error);
    message.error(error.toString());
    if (error instanceof HTTPError) {
      if (error.status === 401) {
        if (route.name !== "login") {
          router.push({
            name: "login",
            query: {
              redirect: location.href.substring(location.origin.length),
            },
          });
        }
      } else if (error.status === 403) {
        configStore.fetchConfigLock();
      }
    }
  };

  return {
    masterStore,
    configStore,
    storageStore,
    route,
    router,
    dialog,
    message,
    errorHandler,
  };
}
